<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="样品销毁申请">
        <template slot="btn">
          <el-button class="filter-item" plain="" icon="el-icon-refresh-left" size="small"
                     @click="handleBack">返回
          </el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-check" size="small"
                     @click="handleSubmit">提交审核
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">
      <!-- 表单 -->
      <el-form ref="form" :model="form" label-position="left" :rules="rules">
        <el-row :gutter="80">
          <el-col :span="12">
            <el-form-item label="销毁人" label-width="80px" prop="destroy_info.destroy_user_id">
              <el-cascader v-model="form.destroy_info.destroy_user_id" :options="deptOptions"
                           placeholder="请选择销毁人" ref="refHandle" :show-all-levels="false" style="width: 100%"
                           @change="handlDestroy" :props="{ expandTrigger: 'hover' ,label:'name',value:'id'}">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监督人" label-width="80px" prop="destroy_info.supervision_user_id">
              <el-cascader v-model="form.destroy_info.supervision_user_id" :options="deptOptions"
                           placeholder="请选择监督人" ref="refHandle" :show-all-levels="false" style="width: 100%"
                           @change="handlSuprvison"
                           :props="{ expandTrigger: 'hover' ,label:'name',value:'id'}">
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <!--销毁明细-->
        <item-title title="销毁明细" :borderShow="false">
          <template slot="btn">
            <!-- 操作-->
            <div style="margin-bottom: 20px">
              <el-button class="filter-item" type="primary" icon="el-icon-plus" size="small"
                         @click="handlAdd">添加行
              </el-button>
              <el-button class="filter-item" type="danger" icon="el-icon-delete" size="small"
                         @click="handlDele('ss')">
                全部删除
              </el-button>
            </div>
          </template>
        </item-title>

        <!--表格-->
        <el-table :data="form.sample_destroy_info" class="table1" border size="medium">
          <el-table-column label="样品名称" align="center" width="200">
            <template slot-scope="scpoe">
              <el-form-item :prop="'sample_destroy_info.' + scpoe.$index + '.sample_info.name'"
                            size="mini" :rules="{ required: true, message: '请选择样品名称', trigger: 'change'}">
                <div style="display: flex;justify-content: space-between">
                  <el-select v-model="scpoe.row.sample_info.name" filterable
                             :filter-method="handlMethod" clearable style="width: 80%" size="small"
                             @change="(val)=>handlChane(val,scpoe.$index)">
                    <el-option v-for="(item,index) in sampleList" :key="index"
                               :label="item.sample_info? item.sample_info.name : '' "
                               :value="item.sample_info? item.sample_info.name : '' ">
                    </el-option>
                  </el-select>
                  <el-button icon="el-icon-search" type="text"
                             @click.native.stop="handlOpen(scpoe.$index)" size="medium" circle></el-button>
                </div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="样品类别" align="center">
            <template #default="{row}">
              <span v-if="row.sample_info.sample_type_info">
                {{row.sample_info.sample_type_info.same_type_name	}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="批号" align="center">
            <template #default="{row}">
              <span v-if="row.sample_info"> {{handlBatch(row.sample_info.batch_info)}}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column prop="sample_info.attr" label="规格" align="center"/>-->
          <el-table-column prop="project_name" label="所属项目" align="center"/>
          <el-table-column label="留样日期" align="center">
            <template slot-scope="scope">
              <span
                v-if="scope.row.reserve_sample_time">{{ dateFormat1('yyyy-mm-dd HH:MM:SS',scope.row.reserve_sample_time)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="destroy_num" label="留样数量" align="center" width="100"/>
          <el-table-column prop="destroy_num" label="销毁数量" align="center" width="100"/>
          <el-table-column label="销毁原因" align="center" width="200">
            <template slot-scope="props">
              <el-form-item :prop="'sample_destroy_info.' + props.$index + '.reason'"
                            :rules="{ required: true, message: '请输入销毁原因', trigger: 'blur'}">
                <el-input v-model="props.row.reason" size="small"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="操作" align="center" width="50">
            <template slot-scope="scope">
              <el-button style="color:red" type="text" size="medium" icon="el-icon-delete"
                         @click="handlDele(scope.$index)">
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <!--对话框 -->
    <el-dialog title="选择样品" :visible.sync="open" width="1150px" append-to-body
               :before-close="cancel" :close-on-click-modal="false" v-if="open">
      <el-form v-model="queryParams" label-width="100" :inline="true">
        <el-form-item label="留样有效期至">
          <el-date-picker v-model="value" type="daterange" range-separator="至" @input="handlDate"
                          start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="所属项目">
          <el-select v-model="queryParams.project_id" clearable placeholder="请选择">
            <el-option v-for="item in projectList" :key="item.value" :label="item.project_name"
                       :value="item.project_id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="样品关键字">
          <el-input v-model="queryParams.select_str" placeholder="请输入样品关键字"/>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" size="small"
                     @click="handleQuery">查询
          </el-button>
        </el-form-item>
      </el-form>
      <div id="scrollBox">
        <el-table ref="multipleTable" :data="tableOpen" tooltip-effect="dark" border size="medium"
                  :row-key="(row)=>{ return row.id}" style="width: 100%"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" :reserve-selection="true"/>
          <el-table-column prop="reserve_sample_no" label="样品编号" align="center"
                           :show-overflow-tooltip="true"/>
          <el-table-column prop="sample_info.name" label="样品名称" align="center"
                           :show-overflow-tooltip="true"/>
          <el-table-column prop="sample_info.sample_type_name" label="样品类别" align="center"
                           :show-overflow-tooltip="true">
            <template #default="{row}">
              <span v-if="row.sample_info.sample_type_info">
                {{row.sample_info.sample_type_info.same_type_name	}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="批号" align="center" :show-overflow-tooltip="true">
            <template #default="{row}">
              <span v-if="row.sample_info"> {{handlBatch(row.sample_info.batch_info)}}</span>
            </template>
          </el-table-column>
          <!--        <el-table-column prop="sample_info.attr" label="规格" align="center" :show-overflow-tooltip="true"/>-->
          <el-table-column label="生产日期" align="center" :show-overflow-tooltip="true">
            <template #default="{row}">
              <span v-if="row.sample_info && row.sample_info.production_date">
                {{dateFormat1('yyyy-mm-dd',row.sample_info.production_date)}}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="project_name" label="所属项目" align="center"
                           :show-overflow-tooltip="true"/>
          <el-table-column prop="num" label="留样数量" align="center"/>
          <el-table-column label="留样有效期至" align="center" :show-overflow-tooltip="true">
            <template #default="{row}">
              <div>{{dateFormat1('yyyy-mm-dd ',row.expiry_date)}}</div>
              <div>{{calculate(dateFormat1('yyyy-mm-dd ',row.expiry_date))}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="留样时间" align="center" :show-overflow-tooltip="true">
            <template #default="{row}">
              {{dateFormat1('yyyy-mm-dd HH:MM:SS',row.created_at)}}
            </template>
          </el-table-column>
        </el-table>
        <pagination style="display:flex;justify-content:flex-end;" :total="total"
                    :page.sync="queryParams.pager.skip" :limit.sync="queryParams.pager.limit"
                    @pagination="pagination"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" @click="submitOpen"> 确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { projectName } from '@/api/sampleInspection'
  import { sampleList, sampleAllProject, sampleListsss } from '@/api/samples'
  import {
    sampleCreate,
    destroyPeople,
    sampleDetail,
    destroyEdit
  } from '@/api/sampleManagement'

  export default {
    name: 'index',
    data() {
      let checkHandl1 = (rule, value, callback) =>{
        if(value === ''){
          callback(new Error('请选择销毁人'))
        }else{
          if(value === this.form.destroy_info.supervision_user_id){
            callback(new Error('销毁人不能与监督人选择相同'))
          }else{
            callback()
          }
        }
      }
      let checkHandl2 = (rule, value, callback) =>{
        if(value === ''){
          callback(new Error('请选择监督人'))
        }else{
          if(value === this.form.destroy_info.destroy_user_id){
            callback(new Error('监督人不能与销毁人选择相同'))
          }else{
            callback()
          }
        }
      }
      return {
        form: {
          destroy_info: {
            destroy_user_id: '', //销毁人id
            destroy_user_name: '', // 销毁人名称
            supervision_user_id: '', // 监督人id
            supervision_user_name: '' //监督人名称
          },
          sample_destroy_info: [
            {
              sample_info: {
                id: '', //样品id
                name: '', //样品名称
                attr: '', //规格
                batch_number: '', //批号
                sample_type_id: '', //样品类别id
                sample_type_name: '' //样品类别名称
              },
              project_id: '', //所属项目id
              project_name: '', // 所属项目
              destroy_num: 0, //销毁数量
              reason: '', //销毁理由/原因
              reserve_sample_time: '', // 留样时间
              reserve_sample_id: '', //留样id
              id: ''
            }
          ]
        },
        rules: {
          'destroy_info.destroy_user_id': [
            { required: true, validator: checkHandl1, trigger: 'change' }
          ],
          'destroy_info.supervision_user_id': [
            { required: true,  validator: checkHandl2, trigger: 'change' }
          ]
        },
        destroyList: [{ id: '0', name: '黄金糕' }],
        supervisionList: [{ id: '0', name: '黄金糕' }],
        open: false,
        value: [],
        projectData: [],
        sampleList: [],
        tableOpen: [],
        multipleSelection: [],
        select_ids: [],
        queryParams: {
          search_type: 0,
          select_str: '',
          start_time: '',
          end_time: '',
          project_id: '',
          select_ids: [],
          pager: {
            limit: 10,
            skip: 1
          }
        },
        total: 0,
        index: 0,
        projectList: [],
        deptOptions: []
      }
    },

    //是计算属性，也可以理解为一个方法。
    computed: {
      calculate() {
        return function(val) {
          let a = ''
          let date = new Date()
          let year = date.getFullYear()
          let month = date.getMonth() + 1
          month > 10 ? month : `0${month}`
          let day = date.getDate()
          day > 10 ? day : `0${day}`
          let expiry_date = `${year}-${month}-${day}`
          if (new Date(val) < new Date(expiry_date)) {
            a = '已过期'
          }
          return a
        }
      },
      handlBatch() {
        return function(val) {
          let str = ''
          if (val) {
            for (let i = 0; i < val.length; i++) {
              str += val[i].sample_batch
              if (i !== val.length - 1) {
                str = str + '、'
              }
            }
          }
          return str
        }
      }
    },

    //属性是手动定义的所需监听的值
    watch: {},

    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.handlMethod('')
      this.handlSampleAllProject()
      this.handlDestroyPeople()
      if (this.$route.query.s_id) {
        this.handlSampleDetail()
      }
    },

    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },

    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取编辑详情
      handlSampleDetail() {
        sampleDetail(this.$route.query.s_id).then(res => {
          if (res.code === 200) {
            this.form.destroy_info = res.data.reserve_sample_destroy
            this.form.sample_destroy_info = res.data.sample_destroy_info
            console.log(this.form.sample_destroy_info, '-------')
          }
        })
      },

      handlDate(val) {
        if (val === null) {
          this.queryParams.start_time = ''
          this.queryParams.end_time = ''
        } else {
          this.queryParams.start_time = this.dateFormat1(
            'yyyy-mm-dd 00:00:00',
            val[0]
          )
          this.queryParams.end_time = this.dateFormat1(
            'yyyy-mm-dd 23:59:59',
            val[1]
          )
        }
      },
      handlSampleAllProject() {
        sampleAllProject().then(res => {
          if (res.code === 200) {
            this.projectList = res.data
          }
        })
      },

      handlDestroyPeople() {
        destroyPeople().then(res => {
          if (res.code === 200) {
            this.deptOptions = res.data.data || []
          }
        })
      },

      //返回
      handleBack() {
        this.$router.go(-1)
      },

      //销毁人事件
      handlDestroy(val) {
        let index = this.deptOptions.findIndex(a => a.id === val[0])
        if (index !== -1) {
          let ind = this.deptOptions[index].children.findIndex(
            b => b.id === val[1]
          )
          if (ind !== -1) {
            this.form.destroy_info.destroy_user_id = this.deptOptions[
              index
              ].children[ind].id //销毁人id
            this.form.destroy_info.destroy_user_name = this.deptOptions[
              index
              ].children[ind].name // 销毁人名称
          }
        }
      },

      //监督人事件
      handlSuprvison(val) {
        let index = this.deptOptions.findIndex(a => a.id === val[0])
        if (index !== -1) {
          let ind = this.deptOptions[index].children.findIndex(
            b => b.id === val[1]
          )
          if (ind !== -1) {
            this.form.destroy_info.supervision_user_id = this.deptOptions[
              index
              ].children[ind].id //销毁人id
            this.form.destroy_info.supervision_user_name = this.deptOptions[
              index
              ].children[ind].name // 销毁人名称
          }
        }
      },

      //获取样品列表
      async handlMethod(val) {
        this.handlIds()
        let res = await sampleListsss({
          search_type: 0,
          select_str: val,
          select_ids: this.select_ids
        })
        if (res.code === 200) {
          this.sampleList = res.data.data || []
        }
      },

      //样品名称事件
      handlChane(val, index) {
        if (val !== '') {
          this.handlMethod(val)
          let ind = this.sampleList.findIndex(a => a.sample_info.name === val)
          if (ind !== -1) {
            // this.form.sample_destroy_info[index].id = this.sampleList[ind].id;
            this.form.sample_destroy_info[index].project_id = this.sampleList[
              ind
              ].project_id //所属项目id
            this.form.sample_destroy_info[index].project_name = this.sampleList[
              ind
              ].project_name // 所属项目
            this.form.sample_destroy_info[index].destroy_num = this.sampleList[
              ind
              ].num //销毁数量
            this.form.sample_destroy_info[
              index
              ].reserve_sample_time = this.sampleList[ind].created_at // 留样时间
            this.form.sample_destroy_info[
              index
              ].reserve_sample_id = this.sampleList[ind].id //留样id
            this.form.sample_destroy_info[index].sample_info.id = this.sampleList[
              ind
              ].sample_info.id //样品id
            this.form.sample_destroy_info[
              index
              ].sample_info.name = this.sampleList[ind].sample_info.name //样品名称
            this.form.sample_destroy_info[
              index
              ].sample_info.attr = this.sampleList[ind].sample_info.attr //规格
            this.form.sample_destroy_info[
              index
              ].sample_info.batch_info = this.sampleList[
              ind
              ].sample_info.batch_info //批号
            this.form.sample_destroy_info[
              index
              ].sample_info.sample_type_info = this.sampleList[
              ind
              ].sample_info.sample_type_info //样品类别id
            this.form.sample_destroy_info[
              index
              ].sample_info.sample_type_name = this.sampleList[
              ind
              ].sample_info.sample_type_name //样品类别id
          }
          this.handlIds()
        } else {
          this.form.sample_destroy_info[index].reserve_sample_id = ''
          this.handlMethod('')
        }
      },

      //处理样品IDS
      handlIds() {
        let arr = []
        this.form.sample_destroy_info.forEach(item => {
          if (item.reserve_sample_id) {
            arr.push(item.reserve_sample_id)
          }
        })
        this.select_ids = [...new Set(arr)]
        this.queryParams.select_ids = this.select_ids
      },

      //添加行
      handlAdd() {
        this.form.sample_destroy_info.push({
          sample_info: {
            id: '', //样品id
            name: '', //样品名称
            attr: '', //规格
            batch_number: '', //批号
            sample_type_id: '', //样品类别id
            sample_type_name: '' //样品类别名称
          },
          project_id: '', //所属项目id
          project_name: '', // 所属项目
          destroy_num: 0, //销毁数量
          reason: '', //销毁理由/原因
          reserve_sample_time: '', // 留样时间
          reserve_sample_id: '' //留样id
        })
        this.handlMethod('')
      },

      //删除
      handlDele(index) {
        if (index === 'ss') {
          this.form.sample_destroy_info = []
        } else {
          for (let i = 0; i < this.form.sample_destroy_info.length; i++) {
            if (index === i) {
              this.form.sample_destroy_info.splice(i, 1)
              break
            }
          }
        }
        this.handlIds()
      },

      //打开弹框
      handlOpen(index) {
        this.open = true
        this.queryParams.select_ids = this.select_ids
        this.index = index
        this.hanldsampleList()
      },

      //获取弹框列表数据
      hanldsampleList() {
        this.handlIds()
        let data = JSON.parse(JSON.stringify(this.queryParams))
        sampleList(data).then(res => {
          if (res.code === 200) {
            this.tableOpen = res.data.data || []
            this.total = res.data.total
          }
        })
      },

      //页码
      pagination(val) {
        this.queryParams.pager.skip = val.page
        this.queryParams.pager.limit = val.limit
        this.hanldsampleList()
      },

      //查询弹框
      handleQuery() {
        this.queryParams.pager.skip = 1
        this.hanldsampleList()
      },

      //取消
      cancel() {
        this.open = false
        this.queryParams = {
          search_type: 0,
          sample_name: '',
          select_ids: [],
          start_time: '',
          end_time: '',
          pager: {
            limit: 10,
            skip: 1
          }
        }
        this.value = []
        this.$refs.multipleTable.clearSelection()
      },

      //确定
      submitOpen() {
        if (this.multipleSelection.length === 0) {
          this.$message.error('请选择样品')
          return
        }
        let arr = []
        this.multipleSelection.forEach(item => {
          let sample_info = {}
          if (item.sample_info === null) {
            sample_info = {
              id: '', //样品id
              name: '', //样品名称
              attr: '', //规格
              batch_number: '', //批号
              sample_type_id: '', //样品类别id
              sample_type_name: '' //样品类别名称
            }
          } else {
            sample_info = {
              id: item.sample_info.id, //样品id
              name: item.sample_info.name, //样品名称
              attr: item.sample_info.attr, //规格
              batch_number: item.sample_info.batch_number, //批号
              sample_type_id: item.sample_info.sample_type_id, //样品类别id
              sample_type_name: item.sample_info.sample_type_name //样品类别名称
            }
          }
          arr.push({
            sample_info: sample_info,
            project_id: item.project_id, //所属项目id
            project_name: item.project_name, // 所属项目
            destroy_num: item.num, //销毁数量
            reason: '', //销毁理由/原因
            reserve_sample_time: item.created_at, // 留样时间
            reserve_sample_id: item.id //留样id
          })
        })
        this.form.sample_destroy_info.splice(this.index, 1)
        for (let i = arr.length - 1; i > -1; i--) {
          this.form.sample_destroy_info.splice(this.index, 0, arr[i])
        }
        this.handlIds()
        this.cancel()
      },

      //多选事件
      handleSelectionChange(selection) {
        this.multipleSelection = [...new Set(selection)]
      },

      //提交审核
      handleSubmit() {
        if (this.form.sample_destroy_info.length === 0) {
          this.$message.error('请添加样品')
          return
        }

        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.$route.query.s_id) {
              let data = {
                reserve_sample_destroy: this.form.destroy_info,
                sample_destroy_info: this.form.sample_destroy_info
              }
              destroyEdit(data).then(res => {
                if (res.code == 200) {
                  this.$message.success('编辑成功')
                  this.$route.params.refresh = true
                  this.$router.push('/sampleManagement/destruction')
                } else {
                  this.$message.error(res.msg)
                }
              })
            } else {
              this.form.sample_destroy_info.forEach(item => {
                this.$delete(item, 'id')
              })
              sampleCreate(this.form).then(res => {
                if (res.code === 200) {
                  this.$message.success('创建成功')
                  this.$route.params.refresh = true
                  this.$router.push('/sampleManagement/destruction')
                } else {
                  this.$message.error(res.msg)
                }
              })
            }
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>
  /* @import url(); 引入css类 */
  .el-button--text {
    padding: 0;
  }

  ::v-deep .el-dialog__body {
    height: 600px;
    box-sizing: border-box;
  }

  ::v-deep #scrollBox {
    height: 90% !important;
    flex: 1 !important;
    overflow-y: auto !important;
    color: #000;
    font-size: 16px;
  }

  ::v-deep #scrollBox::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  ::v-deep #scrollBox::-webkit-scrollbar-thumb {
    border-radius: 100px;
    background: #cccccc;
  }

  ::v-deep #scrollBox::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
  }

  ::v-deep .table1 tr td {
    padding: 0 !important;
    height: 64px !important;
    overflow: visible !important;
    line-height: 64px;
  }

  ::v-deep .table1 tr td .cell {
    height: 30px !important;
    overflow: visible !important;
    line-height: 30px;
  }

  ::v-deep .el-table {
    overflow: visible !important;
  }

  ::v-deep .el-table__body-wrapper {
    overflow: visible;
  }
</style>
